#!/usr/bin/env python3
# coding=utf-8
# 发送邮件, 支持不同文本, html, 附件
import smtplib
from email.message import EmailMessage
import mimetypes
import os

# username = 'xx'
# password = 'xx'
# mail_from = 'xx'
# smtp_host = 'xx'


def get_smtp_server():
    try:
        smtp_server = smtplib.SMTP(smtp_host)
    except Exception as e:
        # print "[ERROR] failed to init a SMTP instance encapsulates an SMTP connection: %s" % str(e)
        exit(1)

    code = smtp_server.ehlo()[0]
    esmtp_flag = True
    if not (200 <= code < 300):
        esmtp_flag = False
        code = smtp_server.helo()[0]
        if not (200 <= code < 300):
            raise smtplib.SMTPHeloError(code)

    if esmtp_flag and smtp_server.has_extn('starttls'):
        # print "[DEBUG] Negotiating TLS..."
        smtp_server.starttls()  # put the SMTP connection in TLS mode. should then call ehlo() again.
        code = smtp_server.ehlo()[0]
        if not (200 <= code < 300):
            print("[WARN] Couldn't EHLO after starttls()")
            exit(2)
            # print "[DEBUG] Using TLS connection"
            # else:
            # print "[DEBUG] Server does not support TLS, using normal connection"

    try:
        smtp_server.login(username, password)
    except smtplib.SMTPException as e:
        print("[ERROR] Authentication failed: %s" % str(e))
        exit(3)

    return smtp_server


def sendText(mail_to, subject, content, is_html=False):
    '''
    发送MIME类型为text/*的邮件
    :param mail_to: ', '.join(receivers)
    :param subject: mail subject
    :param content: text_content
    :param is_html 是否是html类型的内容
    :return: 
    '''
    smtp = get_smtp_server()
    msg = EmailMessage()
    msg['To'] = mail_to
    msg['From'] = mail_from
    msg['Subject'] = subject
    if is_html:
        msg.set_content(content, subtype='html')
    else:
        msg.set_content(content)

    # body = MIMEText(content, 'html', _charset='utf-8')

    try:
        smtp.send_message(msg)
    except (ValueError, smtplib.SMTPRecipientsRefused, smtplib.SMTPHeloError, smtplib.SMTPSenderRefused,
            smtplib.SMTPDataError) as e:
        print("[ERROR] failed to send mail: %s" % str(e))
    finally:
        smtp.quit()


def sendTextWithAttach(mail_to, subject, content, attach_file):
    '''
    发送MIME类型为text/*的邮件
    :param mail_to: ', '.join(receivers)
    :param subject: mail subject
    :param content: text_content
    :param attach_file 附件文件路径
    :return: 
    '''
    smtp = get_smtp_server()
    msg = EmailMessage()
    msg['To'] = mail_to
    msg['From'] = mail_from
    msg['Subject'] = subject
    msg.set_content(content)
    if os.path.isfile(attach_file):
        # Guess the content type based on the file's extension.
        ctype, encoding = mimetypes.guess_type(attach_file)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        file_name = attach_file.split('/')[-1]  #取附件路径按 / 分隔的最后一个作为附件名
        with open(attach_file, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=file_name)

    try:
        smtp.send_message(msg)
    except (ValueError, smtplib.SMTPRecipientsRefused, smtplib.SMTPHeloError, smtplib.SMTPSenderRefused,
            smtplib.SMTPDataError) as e:
        print("[ERROR] failed to send mail: %s" % str(e))
    finally:
        smtp.quit()


if __name__ == "__main__":
    # sendText("tianzhipeng@miaozhen.com", "test", "test text")
    # sendTextWithAttach("tianzhipeng@miaozhen.com", "test", "test text attach", "/Users/tzp/Downloads/dump.gz")
    sendText("tianzhipeng@miaozhen.com", "test", "<h1>test text html</h1>", True)
